// pages/my/my.js
const config = require('../config')
const { API_BASE_URL } = config;
Page({
  data: {

  },
  onShow() {
    const userInfo = wx.getStorageSync('userInfo');
    console.log(' -----------');
    console.log(userInfo)
    this.setData({
      userInfo:userInfo
    })
    console.log(this.data.userInfo);
  },
  toLogin(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  tochenLogin(){
    let that = this; // 在此保存对 App 实例的引用
    wx.login({
      success: function (loginRes) {
        if (loginRes.code) {
          wx.getUserInfo({
            withCredentials: true, // 非必填, 默认为true
            success: function (infoRes) {
              //获取openid
              wx.request({
                url: `${API_BASE_URL}/user/login/wx_open`,
                data: {
                  code: loginRes.code, // 临时登录凭证
                  rawData: infoRes.rawData, // 用户非敏感信息
                  signature: infoRes.signature, // 签名
                  encryptedData: infoRes.encryptedData, // 用户敏感信息
                  ivStr: infoRes.iv // 解密算法的向量
                },
                success: function (response) {
                  if (response.data.message === "ok") {
                    const token = response.header['satoken'];
                    if (!token) {
                      console.error('没有找到 Token');
                      return;
                    }
                    const userInfo = response.data.data;
                    console.log("Token:", token);
                    console.log("UserInfo:", userInfo);
                    wx.setStorageSync('token', token);
                    wx.setStorageSync('userInfo', userInfo);
                  } else {
                    that.showInfo(res.info);
                  }
                },
                fail: function (error) {
                  //调用接口失败
                }
              });
            },
            fail: function (error) {
              // 获取 userInfo 失败，去检查是否未开启权限
            }
          });
        } else {
          console.log("获取 code 失败");
        }
      },
      fail: function (error) {
        // 调用 wx.login 接口失败
      }
    });

  },
  async loginOut() {
    try {
      // 获取本地存储中的 token
      const token = wx.getStorageSync('token');
      console.log("存储token"+token);
      if (!token) {
        console.warn('没有找到 token');
        return;
      }
  
      // 发送登出请求
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${API_BASE_URL}/user/logout`,
          method: "POST",
          header: {
            'content-type': 'application/json',
            'satoken': `${token}` // 确保这里添加了 token
          },
          success: resolve,
          fail: reject
        });
      });

      console.log(response.data.message);  
      // 检查响应是否成功
      if (response.data.message === "ok") { // 根据实际情况调整
        // 移除本地存储中的用户信息和 token
        wx.removeStorageSync('userInfo');
        wx.removeStorageSync('token');
        // 可选：向用户显示成功的提示信息
        wx.showToast({
          title: '已退出登录',
          icon: 'success',
          duration: 2000
        });
      } else {
        // 显示错误消息给用户
        wx.showToast({
          title: response.data.message || '登出失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('请求错误:', error);
      wx.showToast({
        title: '网络请求失败，请稍后再试',
        icon: 'none',
        duration: 2000
      });
    }
  },
  tomyOrder(){
    wx.navigateTo({
      url: '/pages/my/myOrder/myOrder',
    })
  } ,
  toawaitshop(){
    wx.navigateTo({
      url: '/pages/awaitshop/awaitshop',
    })
  },
  toawaitreceipt(){
    wx.navigateTo({
      url: '/pages/awaitreceipt/awaitreceipt',
    })
  },
  toawaitpay(){
    wx.navigateTo({
      url: '/pages/awaitpay/awaitpay',
    })
  },
  tocomplete(){
    wx.navigateTo({
      url: '/pages/complete/complete',
    })
  }
})